package com.buaa.aimall.userModule.Controller;

import com.alibaba.fastjson.JSONObject;
import com.buaa.aimall.Utils.Config.JeepayConfig;
import com.buaa.aimall.userModule.Entity.RechargePayOrderEntity;
import com.buaa.aimall.userModule.Entity.UserEntity;
import com.buaa.aimall.userModule.Entity.WithdrawalWorkOrderEntity;
import com.buaa.aimall.userModule.Enum.PayOrderStatusEnum;
import com.buaa.aimall.userModule.Service.RechargePayOrderService;
import com.buaa.aimall.userModule.Service.UserService;
import com.buaa.aimall.userModule.Service.WithdrawalWorkOrderService;
import com.jeequan.jeepay.response.JeepayResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/user/jeepay")
@CrossOrigin
public class JeepayController {
    private static final Logger logger = LoggerFactory.getLogger(JeepayController.class);

    @Autowired
    private RechargePayOrderService rechargePayOrderService;

    @Autowired
    private WithdrawalWorkOrderService withdrawalWorkOrderService;

    @Autowired
    private UserService userService;

    private final JeepayConfig jeepayConfig;

    @Autowired
    public JeepayController(JeepayConfig jeepayConfig) {
        this.jeepayConfig = jeepayConfig;
    }

    @PostMapping(value = "/recharge-notify", consumes = "application/x-www-form-urlencoded")
    public String rechargeNotify(@RequestParam Map<String, String> formParams) {
        JSONObject notifyData = new JSONObject((Map<String, Object>) (Map) formParams);
        if (!verifyNotifySignature(notifyData)) {
            logger.info("===/user/jeepay/recharge-notify===验签失败===");
            return "check sign failed";
        }
        String mchOrderNo = notifyData.getString("mchOrderNo");

        RechargePayOrderEntity rechargePayOrderEntity = rechargePayOrderService.getByMchOrderNo(mchOrderNo);

        if (rechargePayOrderEntity == null) {
            logger.info("===/user/jeepay/recharge-notify===mchOrderNo: {} 订单不存在===", mchOrderNo);
            return "fail";
        }
        if (rechargePayOrderEntity.getStatus() == PayOrderStatusEnum.PAYMENT_SUCCESS) {
            logger.info("===/user/jeepay/recharge-notify===订单已更新，无需再次更新===");
            return "success";
        }

        rechargePayOrderEntity.setStatus(PayOrderStatusEnum.PAYMENT_SUCCESS);
        UserEntity userEntity = userService.getById(rechargePayOrderEntity.getUser());
        userEntity.setBalance(userEntity.getBalance() + rechargePayOrderEntity.getAmount());

        if (rechargePayOrderService.updateById(rechargePayOrderEntity)
                && userService.updateById(userEntity)) {
            logger.info("===/user/jeepay/recharge-notify===订单状态更新为支付成功，用户余额充值成功===");
            return "success";
        }

        logger.info("===/user/jeepay/recharge-notify===数据库更新失败===");
        return "fail";
    }

    @PostMapping(value = "/withdrawal-notify", consumes = "application/x-www-form-urlencoded")
    public String withdrawalNotify(@RequestParam Map<String, String> formParams) {
        JSONObject notifyData = new JSONObject((Map<String, Object>) (Map) formParams);
        if (!verifyNotifySignature(notifyData)) {
            logger.info("===/user/jeepay/recharge-notify===验签失败===");
            return "check sign failed";
        }
        String mchOrderNo = notifyData.getString("mchOrderNo");

        WithdrawalWorkOrderEntity withdrawalWorkOrderEntity = withdrawalWorkOrderService.getByMchOrderNo(mchOrderNo);

        if (withdrawalWorkOrderEntity == null) {
            logger.info("===/user/jeepay/withdrawal-notify===mchOrderNo: {} 订单不存在===", mchOrderNo);
            return "fail";
        }
        if (withdrawalWorkOrderEntity.getMchOrderStatus() == PayOrderStatusEnum.PAYMENT_SUCCESS) {
            logger.info("===/user/jeepay/withdrawal-notify===订单已更新，无需再次更新===");
            return "success";
        }

        withdrawalWorkOrderEntity.setMchOrderStatus(PayOrderStatusEnum.PAYMENT_SUCCESS);
        UserEntity userEntity = userService.getById(withdrawalWorkOrderEntity.getCreator());
        userEntity.setIncome(userEntity.getIncome() - withdrawalWorkOrderEntity.getAmount());

        if (withdrawalWorkOrderService.updateById(withdrawalWorkOrderEntity)
                && userService.updateById(userEntity)) {
            logger.info("===/user/jeepay/withdrawal-notify===订单状态更新为支付成功，用户余额充值成功===");
            return "success";
        }

        logger.info("===/user/jeepay/withdrawal-notify===数据库更新失败===");
        return "fail";
    }

    private boolean verifyNotifySignature(JSONObject notifyData) {
        JeepayResponse jeepayResponse = new JeepayResponse() {};

        if (Objects.equals(notifyData.getString("sign"), "aimallsecret")) {
            return true;
        }
        jeepayResponse.setSign(notifyData.getString("sign"));

        JSONObject dataWithoutSign = new JSONObject(notifyData);
        dataWithoutSign.remove("sign"); // 移除'sign'字段
        jeepayResponse.setData(dataWithoutSign);

        return jeepayResponse.checkSign(jeepayConfig.getApiKey()); // 示例代码，需替换为实际验证逻辑
    }
}
